import { computed, defineComponent, onMounted, reactive, ref } from "vue";
import styles from "./transactionRecords.module.less";
import { useStore as useUserStore } from "@/store/user";
import { $getAccountList } from "@/api/userCenter/PrePaidDepositAccount/PrePaidDepositAccount";
import useXlsx from "@/hooks/useXlsx";
import { Modal, Progress, Spin } from "ant-design-vue";
export default defineComponent({
  name:'userCenterTransactionRecords',
  setup() {
    const userStore = useUserStore();
    const xlsx = useXlsx();

    const state = reactive({
      accountBalance: '1420.94',
      accumulatedRecharge: '',
      balancePayment: '',
      refund: '',
    })



    const searchForm = reactive({
      startDate: null,   //交易时间
      endDate: null,
      time: [],  //交易时间
      serialNumber: '',  //流水号
      consumptionType: null,//消费类型
    })

    const consumptionTypes = ref([
      {
        label: '订单消费',
        value: 'pay_order',
      },
      {
        label: '订单退款',
        value: 'refund_order',
      },
    ])

    const depositList = reactive({
      list: [],
      columns: [
        {
          title: "编号",
          dataIndex: "id",
          align: "center",
          width: "60px",
        },
        {
          title: "交易时间",
          dataIndex: "create_time",
          align: "center",
          width: "180px",
        },
        {
          title: "交易内容",
          dataIndex: "remark",
          align: "center",
          width: "300px",
        },
        {
          title: "金额（元）",
          dataIndex: "account_data",
          align: "center",
          width: "140px",
        },
        {
          title: "交易方式",
          dataIndex: "type_name",
          align: "center",
          width: "150px",
        },
        {
          title: "类型",
          dataIndex: "from_type",
          align: "center",
          width: "120px",
        },
        // {
        //   fixed: "right",
        //   title: "操作",
        //   dataIndex: "operation",
        //   align: "center",
        //   width: "100px",
        // }
      ],
      pagination: {
        total: 0,
        current: 1,
        pageSize: 10,
      },
      loading: false
    })

    //查询
    const clickSearch = () => {
      getList();
    }
    const reset = () => {
      searchForm.time = [];
      searchForm.serialNumber = '';
      searchForm.consumptionType = null;
    }
    //获取缴存记录
    const getList = () => {
      depositList.loading = true;
      $getAccountList({
        page: depositList.pagination.current,
        limit: depositList.pagination.pageSize,
        order_no: searchForm.serialNumber || undefined,
        create_begin: searchForm.time.length > 1 ? String((new Date(searchForm.time[0]).getTime() / 1000).toFixed(0)) : undefined,
        create_end: searchForm.time.length > 1 ? String((new Date(searchForm.time[1]).getTime() / 1000).toFixed(0)) : undefined,
        verify_status: searchForm.consumptionType || undefined,
      }).then((res: any) => {
        depositList.loading = false;
        depositList.list = res.data?.data || [];
        depositList.pagination.total = res?.data?.total || '';
        depositList.pagination.current = res.data?.current_page || '';
        depositList.pagination.pageSize = res?.data?.per_page || '';
      }).catch(() => {
        depositList.loading = false
      })
    }
    // 表格状态变更
    const tableChangeHandler = (pag: { pageSize: number; current: number }) => {
      depositList.pagination.current = pag.current;
      depositList.pagination.pageSize = pag.pageSize;
      getList();
      // const dom: any = document.getElementById("app");
      // dom.scrollTop = 250;
    };

    onMounted(() => {
      getList();
    })
    //时间change
    const timeChange = () => {
      if (searchForm.time === null) {
        searchForm.time = [];
      }
    }
    //缴存记录
    const PrePaidDepositContent = () => (
      <div class={styles['prePaid-deposit-content']}>
        <div class={styles['search-form']}>
          <div class={styles['search-form-row']}>
            <div class={styles['search-form-item']}>
              <div class={styles['item-label']}>交易时间</div>
              <a-range-picker v-model:value={[searchForm.time]} valueFormat="YYYY-MM-DD" style="margin-left: 10px;" onChange={() => { timeChange() }}></a-range-picker>
            </div>
            <div class={styles['search-form-item']}>
              <div class={styles['item-label']}>流水号</div>
              <a-input style="width:78%;" v-model:value={searchForm.serialNumber}></a-input>
            </div>
          </div>
          <div class={styles['search-form-row']}>
            <div class={styles['search-form-item']}>
              <div class={styles['item-label']}>消费类型</div>
              <a-select
                v-model={[searchForm.consumptionType, "value"]}
                options={consumptionTypes.value}
                style="width:35%;height:32px;margin-right:30px"
                allowClear={true}
                placeholder="请选择"
              >
              </a-select>
              <div class={[styles['item-btn'], styles.plain]} onClick={() => { reset() }}>重置</div>
              <div class={styles['item-btn']} onClick={() => { clickSearch() }}>查询</div>
              <div class={styles['item-btn']} onClick={async () => {
                xlsx.init({
                  limit: 2000,
                  otherParams: {},
                  service: $getAccountList,
                })
                await xlsx.defineList([
                  {
                    label: "编号",
                    value: "id",
                    width: 25,
                  },
                  {
                    label: "交易时间",
                    value: "create_time",
                    width: 25,
                  },
                  {
                    label: "交易内容",
                    value: "remark",
                    width: 25,
                  },
                  {
                    label: "金额（元）",
                    value: "account_data",
                    width: 25,
                  },
                  {
                    label: "交易方式",
                    value: "type_name",
                    width: 25,
                  },
                ]);
                await xlsx.exportToExcel('缴存记录.xlsx');
              }}>导出记录</div>
            </div>
          </div>
        </div>
        <div class={styles['deposit-form']}>
          <div class={styles['statistical']}>共有{depositList.pagination.total || 0}条交易记录</div>
          <a-table
            columns={depositList.columns}
            bordered={true}
            scroll={{ x: "max-content" }}
            dataSource={depositList.list}
            onChange={tableChangeHandler}
            rowKey="id"
            pagination={depositList.pagination}
            loading={depositList.loading}
            v-slots={{
              bodyCell: ({ column, record }: any) => {
                // // 操作栏
                // if (column.dataIndex === "operation") {
                //   return (
                //     <div class={styles['operate']}>
                //       <a-button
                //         type="primary"
                //         size="small"
                //         onClick={() => {
                //           certificatePopupRef.value.open(record)
                //         }}
                //       >查看详情</a-button>
                //     </div>
                //   );
                // }
                if (column.dataIndex === "from_type") {
                  switch (record.from_type) {
                    case 'member_recharge':
                      return '线上充值'
                    case 'offline_recharge':
                      return '转账充值'
                    case 'pay_order':
                      return '订单消费'
                    default:
                      return '订单退款'
                  }
                }
              },
            }}
          />
        </div>
      </div>
    )

    const certificatePopupRef = ref(null as any);
    return () => (
      <div class={styles.PrePaidDepositAccount}>
        <div class={styles['header-box']}>交易记录</div>
        {/* <PaymentAccountBalance /> */}
        <PrePaidDepositContent />
        <Modal
          title={'正在导出记录'}
          visible={['doing'].includes(xlsx.state.running)}
          closable={false}
          footer={null}
        >
          <div class={styles["progress_box"]}>
            {
              xlsx.state.running === "doing" && xlsx.progress.value < 100 && (
                <Progress type="circle" percent={xlsx.progress.value} />
              )
            }
            {
              xlsx.state.running === "doing" && xlsx.progress.value === 100 && (
                <Spin tip="正在导出文件,请勿关闭当前页面..." size="large" />
              )
            }
          </div>
        </Modal>
      </div>
    )
  }
})